package com.usiful.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * 常用函数工具
 * @author [周织能]
 *
 */
public class CommonUtil {

	/**
	 * 获取java文件包名
	 * 
	 * @param javaFile
	 * @return
	 */
	public static String getJavaPackageNameByJavaFile(String javaFile) {
		String pkgname = null, javaContent = null;
		try {
			javaContent = FileUtil.readFile2String(javaFile);
			int idx = javaContent.indexOf("package"), idxN = -1;
			do {
				idxN = javaContent.indexOf('\n');
				javaContent = javaContent.substring(idx, javaContent.length());
			} while (idx > idxN);
			if (idx < idxN) {
				String pkgStr = javaContent.substring(idx + "package".length(), idxN);
				pkgname = pkgStr.replace(";", "").trim();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return pkgname;
	}

	/**
	 * 改变java文件内的R引用
	 * 
	 * @param javaFile
	 * @param newPkgName
	 */
	public static void changeJavaR_Refrence(String javaFile, String newPkgName) {
		if(newPkgName == null || !new File(javaFile).exists()) {
			return;
		}
		String oldR_refrence_Pkg = null, magicStr = ".R;";
		int cutEndIdx = -1, cutStartIdx = -1;
		try {
			String javaContent = FileUtil.readFile2String(javaFile);
			cutEndIdx = javaContent.indexOf(magicStr);
			if (cutEndIdx != -1) {
				oldR_refrence_Pkg = javaContent.substring(0, cutEndIdx);
				cutStartIdx = oldR_refrence_Pkg.lastIndexOf("import");
				oldR_refrence_Pkg = oldR_refrence_Pkg.substring(cutStartIdx + "import".length(), oldR_refrence_Pkg.length());
				oldR_refrence_Pkg = oldR_refrence_Pkg.trim();
				javaContent = javaContent.replace(oldR_refrence_Pkg + ".R;", newPkgName + ".R;");
				System.out.println("javaContent=========>\n" + javaContent);
				FileUtil.writeString2File(javaContent, javaFile);
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 根据java文件的声明获取java文件的包路径(相对src)
	 * 
	 * @return
	 */
	public static String extractJavaPackagePathOfJavaFile(String javaFile) {
		String path = getJavaPackageNameByJavaFile(javaFile);
		if (path != null) {
			path = path.replace(".", PathUtil.getDelimite()).trim();
		}
		return path;
	}
}
